class Solution {
public:
    int sz = 0;
    int x = -1;
    vector<bool> vis;
    unordered_set<int> s;
    int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {
        int n = graph.size();
        vis.resize(n);

        for(auto& e : initial)
        {
            s.insert(e);
        }

        auto dfs = [&](this auto&& dfs,int cur)->void
        {
            vis[cur] = true;
            sz++;
            if(x == -1 && s.count(cur)) x = cur;
            else if(x >= 0 && s.count(cur)) x = -2;

            for(int i = 0;i < n;i++)
            {
                if(graph[cur][i] && !vis[i]) dfs(i);
            }
        };

        int mxsz = 0,mi = -1;
        for(int i : initial)
        {
            if(vis[i]) continue;
            sz = 0;
            x = -1;
            dfs(i);
            if(x >= 0 && (sz > mxsz || (sz == mxsz && x < mi)))
            {
                mi = x;
                mxsz = sz;
            }
        }
        return mi < 0 ? ranges::min(initial) : mi;
    }
};